/**
/ * @author Ramprasad Sivaprakasam (A0092629)
 */

package sg.edu.nus.iss.team4ft.ui;

import javax.swing.*;


import sg.edu.nus.iss.team4ft.service.Address;
import sg.edu.nus.iss.team4ft.service.Customer;
import sg.edu.nus.iss.team4ft.service.CustomerAccount;

import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class CustomerControl extends Panel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CustomerAccount customerAccount = new CustomerAccount();
	private Mode mode;
	
	private JTextField cusNumber = new JTextField(20);
	private JTextField accNumber = new JTextField(20);
	private JTextField firstName = new JTextField(20);
	private JTextField lastName = new JTextField(20);
	private JTextField NRIC = new JTextField(20);
	private JTextField line1 = new JTextField(20);
	private JTextField line2 = new JTextField(20);
	private JTextField city = new JTextField(20);
	private JTextField country = new JTextField(20);
	private JTextField postalCode = new JTextField(20);
	private JTextField contactNumber = new JTextField(20);
	private JTextField interest = new JTextField(20);
	
	private final String mandatory = "*";
	//private Address address;
	private JLabel errorPostalCode = new JLabel();
	private JLabel errorTelephone = new JLabel();
	private Checkbox cbActive = new Checkbox("De-Activate");
	
	public CustomerControl(Mode mode, CustomerAccount customerAccount) throws CloneNotSupportedException{
		this.setPreferredSize(new java.awt.Dimension(300, 600));
		this.customerAccount = customerAccount;
		
		setLayout(new BorderLayout());
		
		this.setMode(mode);
		add("Center", createMainPanel());
		//this.setMode(mode);
		//add("East", createButtonPanel());
	}
	
	public CustomerAccount getCustomerAccount() throws Exception {		
		Address addr = new Address(line1.getText().trim(), line2.getText().trim(), city.getText().trim(), country.getText().trim(), new Integer(postalCode.getText().trim()));
		if(customerAccount == null || customerAccount.getCustomer()==null || customerAccount.getAccount()==null){
			if(contactNumber.getText().trim().equals(""))
				customerAccount = new CustomerAccount(firstName.getText().trim(), lastName.getText().trim(), NRIC.getText().trim(), addr, 0, interest.getText().trim());
			else
				customerAccount = new CustomerAccount(firstName.getText().trim(), lastName.getText().trim(), NRIC.getText().trim(), addr, new Integer(contactNumber.getText().trim()), interest.getText().trim());
		}else{
			Customer c = customerAccount.getCustomer();
			c.setFirstName(firstName.getText().trim());
			c.setLastName(lastName.getText().trim());
			c.setNRIC(NRIC.getText().trim());
			c.setBillingAddress(addr);
			if(!contactNumber.getText().trim().equals("")){
				c.setTelephoneNumber(new Integer(contactNumber.getText().trim()));
			}
			//c.setTelephoneNumber(new Integer(contactNumber.getText().trim()));
			c.setInterest(interest.getText().trim());
			customerAccount.setCustomer(c);
		}
		//customerAccount = new CustomerAccount(firstName.getText().trim(), lastName.getText().trim(), NRIC.getText().trim(), addr, new Integer(contactNumber.getText().trim()), interest.getText().trim());
		
		return customerAccount;
	}
	
	public void setCustomerAccount(CustomerAccount customerAccount) {
		this.customerAccount = customerAccount;
	}
	
	@SuppressWarnings("deprecation")
	private JPanel createMainPanel(){
		JPanel p = new JPanel(new BorderLayout());
		
		JLabel cusNumberL = new JLabel("Customer Number : ");
		JLabel accNumberL = new JLabel("Account Number : ");
		JLabel firstNameL = new JLabel("First Name : ");
		JLabel lastNameL = new JLabel("Last Name : ");
		JLabel NRICL = new JLabel("NRIC : ");		
		
		JLabel line1L = new JLabel("Address Line 1 : ");
		JLabel line2L = new JLabel("Address Line 2 : ");
		JLabel cityL = new JLabel("City : ");
		JLabel countryL = new JLabel("Country : ");
		JLabel postalCodeL = new JLabel("Postal Code : ");
		
		JPanel pLine1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pLine1.add(line1);
		if(mode != Mode.View){
			pLine1.add(new JLabel(mandatory)).setForeground(Color.RED);
		}
		
		JPanel pLine2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pLine2.add(line2);
		if(mode != Mode.View)
			pLine2.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JPanel pCity = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pCity.add(city);
		if(mode != Mode.View)
			pCity.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JPanel pCountry = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pCountry.add(country);
		if(mode != Mode.View)
			pCountry.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JLabel telephoneL = new JLabel("Telephone Number : ");
		JLabel interestL = new JLabel("Interest : ");
		
		JPanel pl = new JPanel(new GridLayout(0, 1));
		
		if(this.mode != Mode.New){
			pl.add(cusNumberL);
			pl.add(accNumberL);
		}
		
		pl.add(firstNameL);
		pl.add(lastNameL);
		pl.add(NRICL);
		pl.add(line1L);
		pl.add(line2L);
		pl.add(cityL);
		pl.add(countryL);
		pl.add(postalCodeL);
		pl.add(telephoneL);
		pl.add(interestL);
		
		JPanel pCusNumber = new JPanel(new FlowLayout(FlowLayout.LEFT));
		if(customerAccount !=  null){
			try {
				if(customerAccount.getCustomer() != null){
					cusNumber.setText(customerAccount.getCustomer().getCustomerId());
				}
			} catch (CloneNotSupportedException e1) {
				e1.printStackTrace();
			}
		}
		
		cusNumber.disable();
		pCusNumber.add(cusNumber);
		
		JPanel pAccNumber = new JPanel(new FlowLayout(FlowLayout.LEFT));
		if (customerAccount != null){
			try {
				if (customerAccount.getAccount() != null){
					accNumber.setText(customerAccount.getAccount().getAccountNumber());
				}
			} catch (CloneNotSupportedException e1) {
				e1.printStackTrace();
			}
		}
		
		accNumber.disable();
		pAccNumber.add(accNumber);
		
		JPanel pFirstName = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pFirstName.add(firstName);
		if(mode != Mode.View)
			pFirstName.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JPanel pLastName = new JPanel();
		pLastName.setLayout(new FlowLayout(FlowLayout.LEFT));
		pLastName.add(lastName);
		if(mode != Mode.View)
			pLastName.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JPanel pNRIC = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pNRIC.add(NRIC);
		if(mode != Mode.View)
			pNRIC.add(new JLabel(mandatory)).setForeground(Color.RED);
		
		JPanel pPostalCode = new JPanel();
		pPostalCode.setLayout(new FlowLayout(FlowLayout.LEFT));
		JPanel pTelephone = new JPanel();
		pTelephone.setLayout(new FlowLayout(FlowLayout.LEFT));
		
		postalCode.addKeyListener(new KeyAdapter() {
	         public void keyTyped(KeyEvent e) {
	           char c = e.getKeyChar();
	           if (!((c >= '0') && (c <= '9') ||
	               (c == KeyEvent.VK_BACK_SPACE) ||
	               (c == KeyEvent.VK_DELETE))) {
	               getToolkit().beep();
	               e.consume();
	           }
	           if (postalCode.getText().length() >= 6){
	        	   showMessage("postal code cannot be more than 6 digits");
	        	   getToolkit().beep();
		           e.consume();
	           }
	         }
		});
		
		pPostalCode.add(postalCode);
		if(mode != Mode.View){
			pPostalCode.add(new JLabel(mandatory)).setForeground(Color.RED);
		}
		pPostalCode.add(errorPostalCode);
		
		contactNumber.addKeyListener(new KeyAdapter() {
	         public void keyTyped(KeyEvent e) {
	           char c = e.getKeyChar();
	           if  (!((c >= '0') && (c <= '9') ||
	               (c == KeyEvent.VK_BACK_SPACE) ||
	               (c == KeyEvent.VK_DELETE))) {
	               getToolkit().beep();
	               e.consume();
	           }
	           if (contactNumber.getText().length() >= 10){
	        	   showMessage("contact number cannot be more than 10 digits");
	        	   getToolkit().beep();
		           e.consume();
	           }
	         }
		});
		
		pTelephone.add(contactNumber);
		pTelephone.add(errorTelephone);
		
		JPanel pInterest = new JPanel(new FlowLayout(FlowLayout.LEFT));
		pInterest.add(interest);
		
		JPanel pActivate = new JPanel(new FlowLayout(FlowLayout.LEFT));
		ItemListener lActive = new ItemListener(){
			@Override
			public void itemStateChanged(ItemEvent arg0) {
				getActivate();
			}
		};
		cbActive.addItemListener(lActive);
		pActivate.add(cbActive);
		
		JPanel pt = new JPanel(new GridLayout(0, 1));
		
		if(this.mode != Mode.New){
			pt.add(pCusNumber);
			pt.add(pAccNumber);
		}
		pt.add(pFirstName);
		pt.add(pLastName);
		pt.add(pNRIC);
		pt.add(pLine1);
		pt.add(pLine2);
		pt.add(pCity);
		pt.add(pCountry);
		pt.add(pPostalCode);
		pt.add(pTelephone);
		pt.add(pInterest);
		
		p.add("West",pl);
		p.add("Center",pt);
		
		if (this.mode != Mode.New){			
			p.add("South", pActivate);
		}
		
		JPanel bp = new JPanel();
		bp.setLayout(new  BorderLayout());
		bp.add("North", p);
		return bp;
	}
	
	public Boolean getActivate(){		
		if (this.cbActive.getState() == true){	
			return true;
		}else{
			return false;
		}
	}
	
	public boolean isValidToSave(){
		if(firstName.getText().trim().equals("") == false 
				&& lastName.getText().trim().equals("") == false 
				&& NRIC.getText().trim().equals("") == false
        		&& line1.getText().trim().equals("") == false 
        		&& line2.getText().trim().equals("") == false 
        		&& city.getText().trim().equals("") == false
        		&& country.getText().trim().equals("") == false 
        		&& Integer.parseInt(postalCode.getText()) != 0){
			try{
				//everything is ok
				return true;
			
			}catch(NumberFormatException ne){
				//one of contact number or postal code is not a valid number
				showMessage("invalid number(s)");
				return false;
			}
		}else{
			//one of these fields is not a valid value
			showMessage("invalid value(s)");
			return false;
		}	
	}

	public Mode getMode() {
		return mode;
	}

	public void setMode(Mode mode) throws CloneNotSupportedException {
		this.mode = mode;
		
		if(this.mode == Mode.New)
			 modeNew();
		else if(this.mode == Mode.Edit)
			 modeEdit();
		else if(this.mode == Mode.View)
			 modeView();
	}
	
	private void modeNew(){
		//Enabled
		changeControlState(true);
		this.cbActive.setEnabled(false);
	}
	
	private void modeEdit() throws CloneNotSupportedException{
		//enabled with values		
		populateValues();
		if(customerAccount.getCustomer() != null){
			if(customerAccount.getCustomer().isActive() == false){
				changeControlState(false);
			}else{
				changeControlState(true);
			}
		}
		
	}
	private void modeView(){
		//disabled  with values
		populateValues();
		changeControlState(false);
	}
	
	public void changeControlState(boolean state){
		this.firstName.setEnabled(state);
		this.lastName.setEnabled(state);
		this.NRIC.setEnabled(state);
		this.line1.setEnabled(state);
		this.line2.setEnabled(state);
		this.city.setEnabled(state);
		this.country.setEnabled(state);
		this.postalCode.setEnabled(state);
		this.contactNumber.setEnabled(state);
		this.interest.setEnabled(state);
		this.cbActive.setEnabled(state);
		if (state == false){
			if (mode != Mode.New){
				try {
					if (this.getCustomerAccount().getCustomer().isActive() == false){
						this.cbActive.setState(true);						
					}
				} catch (CloneNotSupportedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public void populateValues(){
		try {
			if(this.customerAccount != null && this.customerAccount.getCustomer() != null){
				this.firstName.setText(this.customerAccount.getCustomer().getFirstName());
				this.lastName.setText(this.customerAccount.getCustomer().getLastName());
				this.NRIC.setText(this.customerAccount.getCustomer().getNRIC());
				this.line1.setText(this.customerAccount.getCustomer().getBillingAddress().getAddressLine1());
				this.line2.setText(this.customerAccount.getCustomer().getBillingAddress().getAddressLine2());
				this.city.setText(this.customerAccount.getCustomer().getBillingAddress().getCity());
				this.country.setText(this.customerAccount.getCustomer().getBillingAddress().getCountry());
				this.postalCode.setText(this.customerAccount.getCustomer().getBillingAddress().getPostalCode().toString());
				if(this.customerAccount.getCustomer().getTelephoneNumber()!=null){
					this.contactNumber.setText(this.customerAccount.getCustomer().getTelephoneNumber().toString());
				}
				this.interest.setText(this.customerAccount.getCustomer().getInterest());
			}
			
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void showMessage(String text) {
		JOptionPane.showMessageDialog(null,text);
	}
}